package com.yy.bootdemo.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.bootdemo.admin.dao.MenuDao;
import com.yy.bootdemo.admin.dao.RoleMenuDao;
import com.yy.bootdemo.admin.dto.MenDto;
import com.yy.bootdemo.admin.dto.MenuIndexDto;
import com.yy.bootdemo.admin.entity.MyMenu;
import com.yy.bootdemo.admin.service.MenuService;
import com.yy.bootdemo.common.utils.MenuTree;
import com.yy.bootdemo.common.utils.TreeUtil;
import com.yy.bootdemo.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author codermy
 * @createTime 2020/7/10
 */
@Service
@Slf4j
public class MenuServiceImpl  extends ServiceImpl<MenuDao, MyMenu> implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleMenuDao roleMenuDao;


    @Override
    public List<MenDto> buildMenuAll() {
         List<MenDto> list = menuDao.buildAll();
//        List<MenDto> tree = TreeUtil.toTree(list,0);
        MenuTree menuTree =new MenuTree(list);
        List<MenDto>   tree=menuTree.builTree();
        return tree;
    }

    @Override
    public List<MenDto> buildMenuAllByRoleId(Integer roleId) {
        return roleMenuDao.buildMenuByRoleId(roleId);
    }

    /**
     * 如果这里删除了菜单树的父节点，把它的子节点一并删除
     * @param id
     * @return
     */
    @Override
    public R delete(Integer id) {
        Integer count = roleMenuDao.countRoleMenuByRoleId(id);
        if (count == 0){
            menuDao.deleteById(id);
            List<Integer> list = menuDao.selectByParentId(id);
            if(list.size()>0){
                for (Integer parentId: list){
                    menuDao.deleteByParentId(parentId);
                }
                menuDao.deleteByParentId(id);
            }
            return R.ok("删除成功");
        }
        else {
            return R.ok("已经有角色分配该菜单，无法删除");
        }

    }



    @Override
    public List<MenuIndexDto> getMenu(Integer userId) {
        List<MenuIndexDto> list = menuDao.listByUserId(userId);
        List<MenuIndexDto> result = TreeUtil.parseMenuTree(list);
        return result;
    }
}
